package com.ws.universal.tools.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.appcompat.widget.AppCompatEditText;

import com.ws.universal.tools.R;

public class ClearableAppCompatEditText extends AppCompatEditText {
    public ClearableAppCompatEditText(Context context) {
        super(context);
        init(context);
    }

    public ClearableAppCompatEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ClearableAppCompatEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        // 添加删除图标到EditText右侧
        /*Drawable drawable = ContextCompat.getDrawable(context, R.drawable.icon_clear);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            setCompoundDrawables(null, null, drawable, null);
        }*/

        // 监听删除图标的点击事件
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                if (getCompoundDrawables()[2] != null) {
                    boolean tappedX = event.getX() > (getWidth() - getPaddingRight() - getCompoundDrawables()[2].getIntrinsicWidth());
                    if (tappedX) {
                        setText("");
                        return true;
                    }
                }
                return false;
            }
        });

        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence.length() > 0) {
                    setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_clear, 0);
                } else {
                    setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
}
